<?php require_once("common.php");
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Menus extends Common {
	function __construct() {
		parent::__construct("menus");
		
		$this->load->model('menu');
		$this->meta 			= array();
		$this->scripts 			= array();
		$this->styles 			= array();
		$this->title 			= "Menus";
	}

	public function index(){
		$menus = $this->menu->get(array('parent_id'=>NULL))->result_array();
		for($i=0;$i<count($menus);$i++){
			$menus[$i]['childs'] = $this->menu->get(array('parent_id'=>$menus[$i]['menu_id']))->result_array();
		}
		$data = array('menus' 		=> $menus,
					  'flashdata'	=> $this->session->flashdata('form_msg'));
		$this->load->view(ADMIN_DIR."menu/index",$data);
	}
	
	function add(){
		$this->scripts = array('jquery.validate','administrator/form_validation');
		$data = array('parents' => $this->menu->get(array('parent_id'=>NULL))->result_array(),
					  'mode'    => 'Add');
		$this->load->view(ADMIN_DIR."menu/form",$data);
	}
	
	function edit($id){
		$this->scripts = array('jquery.validate','administrator/form_validation');
		$data = array('detail'  => $this->menu->get(array('menu_id'=>$id))->row_array(),
					  'parents' => $this->menu->get(array('parent_id'=>NULL))->result_array(),
					  'mode'    => 'Edit');
		$this->load->view(ADMIN_DIR."menu/form",$data);
	}
	
	function save(){
		$mode = $this->input->post('mode');
		$data_post = array('name' 			=> $this->input->post('name'),
						   'name_in_melayu' => $this->input->post('name_in_melayu'),
						   'parent_id' 		=> ($this->input->post('parent_id') == "" ? NULL : $this->input->post('parent_id')),
						   'url' 			=> $this->input->post('url'),
						   'status' 		=> $this->input->post('status'));
		
		if($mode == 'Add'){
			$success = $this->menu->add($data_post);
		}else{
			$success = $this->menu->edit($this->input->post('menu_id'),$data_post);
		}
		
		if($success){
			$this->session->set_flashdata('form_msg', array('success' =>true, 'msg' => "Menu has been saved."));
		}else{
			$this->session->set_flashdata('form_msg', array('failed' =>true, 'msg' => "Menu can't be saved."));
		}
		redirect(base_url().ADMIN_DIR."menus");
	}
	
	function delete($id){
		if($this->menu->delete($id)){
			$this->session->set_flashdata('form_msg', array('success' =>true, 'msg' => "Menu has been deleted."));
		}else{
			$this->session->set_flashdata('form_msg', array('failed' =>true, 'msg' => "Menu can't be deleted."));
		}
		redirect($_SERVER['HTTP_REFERER']);
	}
}